﻿using HAF.Dispatcher.WorkItem;
using HAF.LogUtility.Assistantor;
using Iptv.MediaReporter.Entity;
using Iptv.MediaReporter.Helper;
using Iptv.MediaReporter.Model;
using RDS.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;

namespace Iptv.MediaReporter.SubItems
{
    /// <summary>
    /// 内容建档工作项
    /// </summary>
    public class MediaRecordItem : BaseWorkerItem, IDisposable
    {
        private LoadConfig _runSiteConfig;
        public void Dispose()
        {
            WriteDebugMessage("内容建档任务结束");
        }

        private void RefreshConfig()
        {
            //获取本地配置文件 每次执行的时候读取，实现热配置
            string loadConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, RuntimeAdapter.PluginDir, "ReportConfig.json");
            ShowDebugMessage("获取本地配置文件{0}", loadConfigPath);
            _runSiteConfig = JsonAssistant.FromFile<LoadConfig>(loadConfigPath);
        }

        public override void ExecItem()
        {
            base.ExecItem();
            RefreshConfig();

            if (WorkItems != null && WorkItems is ProgramEntity)
            {
                ProgramEntity program = WorkItems as ProgramEntity;
                PushMediaRecord(program);
            }
            else
            {
                this.Statu = HAF.Dispatcher.Enum.EnumRunItemStatu.End;
            }
        }

        private void PushMediaRecord(ProgramEntity program)
        {
            try
            {
                ReportRecordData recordData = new ReportRecordData
                {
                    action = "1",
                    dataList = new List<MediaRecordInfo>()
                    {
                        new MediaRecordInfo()
                        {
                            localId = program.MediaID,
                            recordDateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                            collectionId = program.MediaCode,
                            collectionName = program.ProgramName,
                            collectionTotal = program.Counter.ToString(),
                            collectionNumber = "1",
                            licenseNum = string.IsNullOrEmpty(program.LicenseNum) ? "无": program.LicenseNum,
                            producer = string.IsNullOrEmpty(program.ContentProvider) ? "SCTV": program.ContentProvider,
                            releaseYear = program.ReleaseYear,
                            releaseDate = string.IsNullOrEmpty(program.ReleaseDate) ? program.CreateTime.ToString("yyyy-MM-dd") : program.ReleaseDate
                        }
                    }
                };

                string postData = JsonAssistant.Serialize(recordData);
                ShowDebugMessage("建档请求数据为 {0}", postData);
                string responseStr = WebHelper.GetHttpResponse(_runSiteConfig.ReportApiUrl, "Post", "application/json", postData);
                ShowDebugMessage("建档上报响应数据为 {0}", responseStr);
                //需要取返回的GUID值
                if (!string.IsNullOrEmpty(responseStr))
                {
                    var recordResult = JsonAssistant.Deserialize<ReportResultData>(responseStr);
                    if (recordResult != null)
                    {
                        WorkOutMessage outTaskMessage = new WorkOutMessage();
                        outTaskMessage.ID = program.MediaID;
                        if (recordResult.data != null && recordResult.data.Count > 0)
                        {
                            string mediaGuid = recordResult.data[0].guid;
                            outTaskMessage.Code = int.Parse(recordResult.code);
                            outTaskMessage.Token = mediaGuid;
                            ShowDebugMessage(mediaGuid);
                        }
                        CallBack(program.MediaID, outTaskMessage);
                        //暂停10秒
                        Thread.Sleep(10 * 1000);
                        //回执正常或者提示重复
                        EndProcess(WorkID, recordResult.code == "0" || recordResult.data[0].errorMessage.IndexOf("2003") > 0);
                    }

                    //打印失败信息
                    ShowDebugMessage(recordResult.message);
                }
            }
            catch (Exception ex)
            {
                EndProcess(WorkID, false);
                ShowErrMessage(ex.ToString());
            }
        }
    }
}
